<?php

class Admin_knowledges_type_Controller extends Template_Controller {

	

	public $search;

	public $template = 'admin/index';

	

    public function __construct()

    {

        parent::__construct();

        

        $this->search = array('keyword' => '','page' => 0);

        

        $this->_get_submit();

    }

    

	public function __call($method, $arguments)

	{

		// Disable auto-rendering

		$this->auto_render = FALSE;

	}

	

	function _get_submit()

	{

		if($this->session->get('error_msg'))

			$this->template->error_msg = $this->session->get('error_msg');

		if($this->session->get('warning_msg'))

			$this->template->warning_msg = $this->session->get('warning_msg');

		if($this->session->get('success_msg'))

			$this->template->success_msg = $this->session->get('success_msg');

		if($this->session->get('info_msg'))

			$this->template->info_msg = $this->session->get('info_msg');

		if($this->session->get('frm'))			

			$this->template->content->mr = $this->session->get('frm');

	}

	

    public function index()

    {	

        $this->showlist();

    }

    

    private function _list_language()

    {

		$model_lang = new Language_Model();		

		$this->template->content->list_language = $model_lang->get_with_active();

	}

	

	public function _show_knowledges_type($id='')

	{

		if($id)

			$this->db->where('knowledges_type.knowledges_type_id',$id);

		$model = new Knowledges_type_Model();    	

    	$mlist = $model->get();

    	for($i=0; $i<count($mlist); $i++)

		{

			$model_lang = new Language_Model();			

			$list_lang = $model_lang->get_with_active();

			for($j=0; $j<count($list_lang); $j++)

			{

				$model_content = new Knowledges_type_content_Model();

				$this->db->where('knowledges_type_id',$mlist[$i]['knowledges_type_id']);

				$this->db->where('languages_id',$list_lang[$j]['languages_id']);

				$list = $model_content->get();

				//$list = $model_content->get($mlist[$i]['knowledges_type_id'],$list_lang[$j]['languages_id']);

				if($list){

				$list = array_merge($mlist[$i],$list[0]);				

				}	

				$list_lang[$j] = $list;	

			}

			$mlist[$i]['languages'] = $list_lang;

		}

		return $mlist;

	}

	

    public function showlist()

    {

    	$this->template->content = new View('admin_knowledges_type/list');

    		

		//Assign

		$this->template->content->keyword = $this->search['keyword'];

		

		$this->where_sql();

		

		//Pagination

    	$this->pagination = new Pagination(array(

    		'base_url'    => 'admin_knowledges_type/search/',

		    'uri_segment'    => 'page',

		    'total_items'    => ORM::factory('knowledges_type')->count_all(),

		    'items_per_page' => $this->site['site_num_line2'],

		    'style'          => 'classic',

		));

		$this->db->limit($this->pagination->items_per_page,$this->pagination->sql_offset);

    	

    	$this->where_sql();

    	$mlist = $this->_show_knowledges_type();

    	$this->template->content->mlist = $mlist;

    	$this->_list_language();

    	$this->_get_submit();

    }

    

    public function where_sql()

    {

    	if($this->search['keyword'])

    		$this->db->like('knowledges_type_title',$this->search['keyword']);

    }

    

    public function search()

    {    	

    	//Get    	

    	if($this->session->get('sess_search')){			

			$this->search = $this->session->get('sess_search');

		}

		

		$keyword = $this->input->post('txt_keyword');

		if(isset($keyword)){    		

			$this->search['keyword'] = $keyword;

		}

		

		//Page

		$page = $this->uri->segment('page');

		if($page)

			$this->search['page'] = $page;

			

		//Set

		$this->session->set_flash('sess_search',$this->search);

		

		$this->showlist();

    }

    

    public function create()

    {

    	$this->template->content = new View('admin_knowledges_type/frm');

    	$this->_list_language();
		
		$model = new Knowledges_type_Model();
		$mr = $model->count_row();
		$this->template->content->mr = $mr;

    }

    

    public function edit($id)

    {	

    	$this->template->content = new View('admin_knowledges_type/frm');

    	$this->_list_language();

    	$list = $this->_show_knowledges_type($id);

    	$mr = $list[0]['languages'];
print_r($mr);
		$this->template->content->mr = $mr;

    }

    

    private function _get_record()

    {

    	$form = array

	    (

	    	'hd_id'	=> '',

	    	'txt_sort_order' => '',

	        'sel_status' => '',

			'txt_image'=>'',

	    );

		

		$model_lang = new Language_Model();

		$list = $model_lang->get_with_active();	

		for($i=0; $i<count($list); $i++)

		{

			$form['txt_title'.$list[$i]['languages_id']] = '';

			$form['txt_description'.$list[$i]['languages_id']] = '';

			

		}

	 

		$errors = $form;

		

		if($_POST)

    	{

    		$post = new Validation($_POST);

    		

			$post->pre_filter('trim', TRUE);

			for($i=0; $i<count($list); $i++){

				$post->add_rules('txt_title'.$list[$i]['languages_id'],'required');

				$post->add_rules('txt_description'.$list[$i]['languages_id'],'required');

				

			}

				

			if($post->validate())

 			{

 				$form = arr::overwrite($form, $post->as_array());

 				return $form; 				

			} else {

				$errors = arr::overwrite($errors, $post->errors('knowledges_type_validation'));

				$str_error = '';

	            for($i=0; $i<count($list); $i++)

				{

					if ($errors['txt_title'.$list[$i]['languages_id']])

						$str_error .= $errors['txt_title'.$list[$i]['languages_id']].'<br>';

				}

				for($i=0; $i<count($list); $i++)

				{

					if ($errors['txt_description'.$list[$i]['languages_id']])

						$str_error .= $errors['txt_description'.$list[$i]['languages_id']].'<br>';

				}

				

				$this->session->set_flash('error_msg',$str_error);

				

				$hd_id = $this->input->post('hd_id');

				if($form['hd_id'])

					url::redirect('admin_knowledges_type/edit/'.$form['hd_id']);

				else

					url::redirect('admin_knowledges_type/create');

				die();

			}

        }

    }

    private function _get_image($name)

	{

		//============Upload==============================	

		// uses Kohana upload helper	

		

		$_FILES = Validation::factory($_FILES)

			->add_rules($name, 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');

			

		if ($_FILES[$name]['error']==0)

		{

			//delete file if have upload image

			//if(file_exists($path_filedel)) unlink($path_filedel);

			

			// Temporary file name

			 $namefile = $_FILES[$name]['name'];
			// Temporary file name
			$filename = upload::save($name,$namefile);

			// Resize, sharpen, and save the image

			//print_r($_FILES['txt_image']);

			//exit();

			Image::factory($filename)

				//->resize(250, 250,Image::AUTO)

				->save(DOCROOT.'uploads/knowledges/'.basename($filename));

		 	

			// Remove the temporary file

			unlink($filename);

		 

			// Redirect back to the account page

			return basename($filename);

		} else {

			if ($hd_old_image)

				return $hd_old_image;

			else

				return '';

		}

	}

    private function _save_knowledges_type($hd_id,$record)

    {

		if(!$hd_id){

			$result = ORM::factory('knowledges_type');

			$result->knowledges_type_create_date = time();

		} else {

			$result = ORM::factory('knowledges_type',$hd_id);

		}

		$result->knowledges_type_sort_order = $record['txt_sort_order'];

		$result->knowledges_type_status = $record['sel_status'];

		

		if($_FILES['txt_image']['name']!="")

		$result->knowledges_type_image = $this->_get_image('txt_image');

		$result->knowledges_type_update_date = time();

		

		$hd_id = $result->save();

		return $hd_id;

	}

	

	private function _save_knowledges_type_content($hd_id,$record)

	{

		$model_lang = new Language_Model();

		$list = $model_lang->get_with_active();

	
		for($i=0; $i<count($list); $i++)

		{

			$model_knowledges_type_content = new Knowledges_type_content_Model();

			$result = $model_knowledges_type_content->get($hd_id,$list[$i]['languages_id']);


			if($result)

			{

				$this->db->update('knowledges_type_content', 

					array('knowledges_type_title' => $record['txt_title'.$list[$i]['languages_id']],

						  'knowledges_type_description' => $record['txt_description'.$list[$i]['languages_id']],

						 

						  ), 

					array('knowledges_type_id' => $hd_id,

						  'languages_id' => $list[$i]['languages_id']

						 )

					);

			} else {

				$this->db->insert('knowledges_type_content',									

					array('knowledges_type_id' => $hd_id,

						  'languages_id' => $list[$i]['languages_id'],

						  'knowledges_type_title' => $record['txt_title'.$list[$i]['languages_id']],

						  'knowledges_type_description' => $record['txt_description'.$list[$i]['languages_id']]

						)

				);

			}

		}

	}

	

    public function save()

    {

    	$hd_id = $this->input->post('hd_id');

    	

    	$record = $this->_get_record();

		

		if($record)

		{

			$hd_id1 = $this->_save_knowledges_type($hd_id,$record);

			$this->_save_knowledges_type_content($hd_id1,$record);

			

			if(!$this->input->post('hd_id'))

				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_add'));

			else

				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));

		}

		url::redirect('admin_knowledges_type');

		die();    	

    }

    

    public function saveall()

    {

    	$arr_id = $this->input->post('chk_id');

		

		if(is_array($arr_id)){

			$sel_action = $this->input->post('sel_action');

		

			if($sel_action == 'delete')	{

				$id = ORM::factory('knowledges_type')->delete_all($arr_id);

				if($id)

					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_del'));

			} elseif($sel_action == 'block') {

				foreach($arr_id as $arr => $id){

					$result = ORM::factory('knowledges_type',$id);

			    	$result->knowledges_type_status = 0;

			    	$id = $result->save();

		    	}

		    	if($id)

					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));

			} elseif($sel_action == 'active')

			{

				foreach($arr_id as $arr => $id){

					$result = ORM::factory('knowledges_type',$id);

			    	$result->knowledges_type_status = 1;

			    	$id = $result->save();

		    	}

		    	if($id)

					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));

			}			

		} else {

			$this->session->set_flash('warning_msg',Kohana::lang('errormsg_lang.msg_data_error'));

		}

		url::redirect('admin_knowledges_type/search');		

		die();

    }

    

    public function delete($id)

    {

    	$status = $this->db->delete('knowledges_type',array('knowledges_type_id' => $id));

    	if(count($status)>0)

		{

			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_del'));

		}

    	url::redirect('admin_knowledges_type/search');

    	die();

    }

    public function delete_image($id)

	{

		$this->db->select();

		$this->db->from('knowledges_type');

		$this->db->where('knowledges_type_id',$id);

		$model = $this->db->get();

		$arrKnowledges = $model->result_array(false);

		$imageName= $arrKnowledges[0]['knowledges_type_image'];

		if($imageName)

		{

			$path_filedel = './uploads/knowledges_type/'.$imageName;

		} 

			

		if($path_filedel)

		{

			if(file_exists($path_filedel)) unlink($path_filedel);

						

		}

		

		$result = ORM::factory('knowledges_type',$id);

		$result->knowledges_type_image = '';

		$result->save();

		url::redirect('admin_knowledges_type/edit/'.$id); 

	}

    public function setstatus($id,$status)

    {

    	$status = $this->db->update('knowledges_type',array('knowledges_type_status' => $status),array('knowledges_type_id' => $id));

    	if(count($status)>0)

		{

			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_status_change'));

		}

    	url::redirect('admin_knowledges_type/search'); 

    	die();

    }
	public function top($id)
    {
    	$model = new Knowledges_type_Model();
		$max = $model->count_row();
		$status = $this->db->update('knowledges_type',array('knowledges_type_sort_order' => $max[0]['max']+1),array('knowledges_type_id' => $id));
		$mr = $model->get_oder();
		//print_r($max);
		//print_r($mr);
		//die();
		for($i=0;$i<count($mr);$i++){
		$this->db->update('knowledges_type',array('knowledges_type_sort_order' => $i+1),array('knowledges_type_id' => $mr[$i]['knowledges_type_id']));
		}
    	url::redirect('admin_knowledges_type/search'); 
    	die();
    }

}

?>